var addrbill = require('../../../../sys/sys_addr.js')
var behaviorsbasicform = require('../../../behavior/basicform')

var acttoolxv2 = require('../../../../sys/toolv2');
var userlocationv2 = require('../../../../../xc/sys/location/userlocationv2')

Component({
  behaviors: [behaviorsbasicform],
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    delivery_config: {
      type: Object,
      value: null
    },
    clubinfo: {
      type: Object,
      value: null
    },

    optype: {
      type: String,
      value: "full" //nohead //full
    },
    // optype: {
    //   type: Object,
    //   value:{ openloacion: -1 }      //nohead //full
    // },  
    navCur: {
      type: String,
      value: "0",
      observer: function (newVal, oldVal) {
        if (newVal == 3 && newVal !== oldVal) {

          this.calcdistance();

        }

      }
    },
    themcolor: {
      type: Object,
      default: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    op: "",

    issubmited: false,
    model: {}
  },
  ready() {
    var app = getApp();


    this.loadaddr();


  },

  /**
   * 组件的方法列表
   */
  methods: {


    loadaddr() {

      var that = this;

      var model = that.data.model
      var app = getApp();
      if (app.globalData.member.memberinfo) {
        model["name"] = app.globalData.member.memberinfo.name
        model["phone"] = app.globalData.member.memberinfo.phone
      }
      var that = this;
      userlocationv2.lastaddr().then(function (resut) {
        if (resut["status"] == 1) {
          that.transformlocationaddr(model, resut.obj)
        }
      })



    },
    /**2  */
    transformlocationaddr(model, addinfo, itype) {
      var that = this;
      if (itype == 2) {

        model["lat"] = addinfo["latitude"]
        model["lng"] = addinfo["longitude"]
        model["addrinfo"] = addinfo["address"]
        model["addrmoreinfo"] = addinfo["name"]
        model["addrname"] = addinfo["name"]

        if (addinfo.xcaddr) {
          var addrlen = addinfo.xcaddr.length
          var fields = ["province", "city", "county"]
          for (var i = 0; i < addrlen; i++) {
            model[fields[i]] = addinfo.xcaddr[i];
          }
        }

      } else {
        model["city"] = addinfo["city"]
        model["county"] = addinfo["district"]
        model["countycode"] = addinfo["adcode"]
        model["province"] = addinfo["province"]
        model["lat"] = addinfo["lat"]
        model["lng"] = addinfo["lng"]
        model["addrinfo"] = addinfo["addrinfo"]
        model["addrname"] = addinfo["addrname"]
      }


      if (this.data.clubinfo) {
        var clubinfo = this.data.clubinfo
        var app = getApp()
        var distance = app.toolv2.distanceByLnglat(model.lng, model.lat, clubinfo.lng, clubinfo.lat)
        model["distance"] = distance

      }
      that.setData({
        model
      })
      if (that.data.optype == "nohead") {
        that.triggerEvent("noheadchange", model)
      }

    },
    calcdistance() {
      var model = this.data.model;
      var updatemodel = {};

      var clubinfo = this.data.clubinfo


      if (clubinfo && model.lat > 0) {


        var app = getApp();
        var distance = app.toolv2.distanceByLnglat(model.lng, model.lat, clubinfo.lng, clubinfo.lat)

        updatemodel['model.distance'] = distance

      } else {
        updatemodel['model.distance'] = null;
      }
      this.setData(updatemodel)
    },

    showop(op, model, waddr) {
      var updatemodel = {}
      updatemodel["op"] = op;
      if (!model) {
        model = this.clearmodel(true)
      }
      if (waddr) {
        model = this.transformwaddr(model, waddr)
      }
      updatemodel["model"] = model
      updatemodel["issubmited"] = false
      this.setData(updatemodel)
    },

    transformwaddr(model, waddr) {
      model["province"] = waddr["provinceName"]
      model["city"] = waddr["cityName"]
      model["county"] = waddr["countyName"]
      model["addrinfo"] = waddr["detailInfo"]
      model["name"] = waddr["userName"]
      model["phone"] = waddr["telNumber"]
      model["countycode"] = waddr["nationalCode"]
      return model;
    },

    hideform() {
      this.setData({
        op: ''
      })

    },
    chooseLocation(ev) {
      var mydata = ev;
      var that = this;
      var model = that.data.model
      model["province"] = ev.province;
      model["city"] = ev.city;
      model["county"] = ev.district;
      model.addrname = mydata["name"];
      model.addrinfo = mydata["address"];
      model.lat = mydata["latitude"];
      model.lng = mydata["longitude"];
      that.setData({
        model
      })
      this.calcdistance();
      if (that.data.optype == "nohead") {
        that.triggerEvent("noheadchange", model)
      }

    },
    chosepostion: function (e) {
      var delivery_config = this.data.delivery_config
      var model = this.data.model
      var that = this;
      if (delivery_config.loaciontype == 1) {
        var qqstylemap = this.selectComponent("#qqstylemap")
        var mode = 1;
        if (this.data.navCur == 3) {
          //域名限制
          mode = 2
        }
        qqstylemap.showmap(mode, model, delivery_config.intracity)
        return;
      } else if (delivery_config.loaciontype == 2) {
        acttoolxv2.forcechooseLocation().then(function (res) {
          if (res["status"] == 1) {
            that.transformlocationaddr(model, res["obj"], res["type"])

          }
        })


        return;


      }
      return
    },
    chooseaddress: function (e) {
      var data = e.detail;
      var model = this.data.model;
      model.province = data[0].name;
      model.city = data[1].name;
      model.county = data[2].name;
      model.countycode = data[2].id;
      this.setData({
        model
      })

      if (that.data.optype == "nohead") {
        that.triggerEvent("noheadchange", model)
      }
    },
    //选择地区
    pickerblock: function () {
      var model = this.data.model
      this.selectComponent("#picker").setinitdata(model.province, model.city, model.county);
    },
    //地址提交
    addrfromsubit(e, resolve) {
      var model = this.data.model;
      var that = this;
      if (!resolve) {
        resolve = function (nreslt) {

        }
      }

      if (that.data.navCur == 3) {
        if (model.lat == 0 || !model.lat) {
          wx.showToast({
            title: '请选择地址',
          })
          resolve({
            status: -1
          })
          return
        }
      }
      var vdata = {
        "name": ["", "收货人姓名不能为空"],
        "phone": ["", "手机不能为空"],
        "addrinfo": ["", "详细地址不能为空"]
      }
      var errors = [];
      for (var a in vdata) {
        if (!model[a] || model[a] == vdata[a][0]) {
          errors.push(vdata[a][1])
        }
      }
      if (errors.length > 0) {
        wx.showModal({
          title: '错误',
          content: errors.join("\r\n"),
        })
        that.setData({
          issubmited: true
        })
        resolve({
          status: -1
        })
      } else {
        if ((!model.county) || (!model.province) || (!model.city)) {
          wx.showModal({
            title: '错误',
            content: "请选择地区",
          })
          this.setData({
            issubmited: true
          })
          resolve({
            status: -1
          })
          return false
        }
      var app = getApp();

        app.xc_sys_config.authop.oppower("login").then(function (res) {

          addrbill.addormodify(model).then(function (ret) {

            if (ret["code"] == "success") {
              if (model.id == 0 || !model.id) {
                model.id = ret["id"]
              }
              that.triggerEvent("addfun", model)
              if (that.data.optype != 'nohead') {
                wx.showToast({
                  title: '操作成功',
                })
              }
              that.setData({
                op: ""
              })
              resolve({
                status: 1,
                obj: model
              })
            } else {
              resolve({
                status: -1
              })
              wx.showToast({
                title: '操作失败',
              })
            }

          })
        })


      }
    },

    selectedaddr(ev) {
      var that = this;
      var detail = ev.detail
      var model = that.data.model
      for (var a in detail) {
        model[a] = detail[a];
      }
      that.setData({
        model
      })
      this.calcdistance();

      if (that.data.optype == "nohead") {
        that.triggerEvent("noheadchange", model)
      }

    },
    //清空数据
    clearmodel(black) {
      var clearupdate = {
        addrmodel: {
          isdefault: "-1",
          addrinfo: "",
          lat: 0,
          lng: 0,
          region: [],
          phone: "",
          name: ""
        }
      }
      if (black) {
        return clearupdate.addrmodel
      } else {
        this.setData(clearupdate)
      }
    }
  }
})